package exer;

/**
 * @author tongchen
 * @create 2022-10-17 11:44
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] tokens = {"2", "1", "+", "3", "*"};
        System.out.println(solution.evalRPN(tokens));
       String []token1= {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        System.out.println(solution.evalRPN(token1));
    }

    public int evalRPN(String[] tokens) {
        //建立栈
        java.util.Stack<Integer> stack = new java.util.Stack<>();
        int sum = 0;
        for (int i = 0; i < tokens.length; i++) {
            if (isNumeric2(tokens[i])) {
                //进行入栈操作
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                int top = stack.pop();
                int second = stack.pop();
                switch (tokens[i].charAt(0)) {
                    case '*':
                        int sum1 = second * top;

                        stack.push(sum1);
                        break;
                    case '/':
                        sum1 = second / top;

                        stack.push(sum1);
                        break;
                    case '+':
                        sum1 = second + top;

                        stack.push(sum1);
                        break;
                    case '-':
                        sum1 = second - top;

                        stack.push(sum1);
                        break;

                }

            }
        }
        sum = stack.pop();

        return sum;
    }
    public boolean isNumeric2(String str) {
        return str != null && str.matches("-?\\d+(\\.\\d+)?");
    }

}

